<?php

namespace App\Models;

use App\Tools\Markdowner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Article extends Model
{
    use SoftDeletes;
    protected $table = 'articles';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['published_at', 'created_at', 'deleted_at'];

    protected $casts = [
        'content' => 'array',
    ];

    protected $fillable = [
        'user_id',
        'last_user_id',
        'category_id',
        'title',
        'slug',
        'page_image',
        'content',
        'meta_description',
        'is_draft',
        'published_at',
    ];

    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;
        $this->setUniqueSlug($value, Str::random(5));
    }

    public function setUniqueSlug($value, $extra)
    {
        //TODO::集成翻译
        $slug = Str::slug($value.'-'.$extra);
        if (static::whereSlug($slug)->exists()) {
            $this->setUniqueSlug($slug, (int) $extra + 1);
            return;
        }
        $this->attributes['slug'] = $slug;
    }

    public function setContentAttribute($value)
    {
        $html = (new Markdowner())->convertMarkdownToHtml($value);
        $data = [
            'raw' => $value,
            'html' => $html,
        ];
        $this->attributes['content'] = json_encode($data,JSON_UNESCAPED_UNICODE);
        $this->attributes['meta_description'] = str_limit(strip_tags($html),150);
    }

    public function setPageImageAttribute($value){
        $this->attributes['page_image'] = str_replace('_','/',$value);
    }



    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

}
